package org.tio.freemarker;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.freemarker.compress.css.TioCssCompressor;
import org.tio.freemarker.compress.html.TioHtmlCompressor;
import org.tio.freemarker.compress.js.TioJsCompressor;
import org.tio.freemarker.init.PropInit;
import org.tio.freemarker.model.Root;
import org.tio.utils.freemarker.FreemarkerUtils;
import org.tio.utils.json.Json;

import com.jfinal.kit.PropKit;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import jodd.io.FileNameUtil;
import jodd.io.FileUtil;

/**
 * @author tanyaowu 
 * 2017年11月13日 下午3:33:54
 */
public class TioWebpackBuildStarter {
	private static Logger log = LoggerFactory.getLogger(TioWebpackBuildStarter.class);

	/**
	 * 
	 * @author tanyaowu
	 */
	public TioWebpackBuildStarter() {
	}

	static Root model = null;

	/**
	 * @param args
	 * @author tanyaowu
	 * @throws IOException 
	 */
	public static void main(String[] args) throws Exception {

		//		System.getProperty("src");
		//		System.getProperty("target");

		try {
			PropInit.init();

			model = null;
			if (args != null && args.length > 0) {
				String modelFilePath = args[0];

				String modelAbsFile = com.xiaoleilu.hutool.io.FileUtil.getAbsolutePath("classpath:" + modelFilePath);
				File modelFile = new File(modelAbsFile);
				log.info("modelAbsFile:{}", modelAbsFile);
				String content = com.xiaoleilu.hutool.io.FileUtil.readString(modelFile, "utf-8");
				model = Json.toBean(content, Root.class);
			}

			String src = PropKit.get("http.page");

			String target = PropKit.get("build.to");

			File srcDir = new File(src);
			if (!srcDir.exists()) {
				log.error("源目录{}不存在", srcDir.getCanonicalPath());
				System.exit(1);
			}

			File targetDir = new File(target);
			if (!targetDir.exists()) {
				targetDir.mkdirs();
			}

			FileUtil.copy(targetDir.getCanonicalPath(), targetDir.getCanonicalPath() + "_back");

			FileUtil.cleanDir(targetDir);

			Configuration cfg = new Configuration(Configuration.getVersion());

			// Specify the source where the template files come from. Here I set a
			// plain directory for it, but non-file-system sources are possible too:
			cfg.setDirectoryForTemplateLoading(srcDir);

			// Set the preferred charset template files are stored in. UTF-8 is
			// a good choice in most applications:
			cfg.setDefaultEncoding("UTF-8");

			// Sets how errors will appear.
			// During web page *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER is better.
			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

			// Don't log exceptions inside FreeMarker that it will thrown at you anyway:
			cfg.setLogTemplateExceptions(true);

			// Wrap unchecked exceptions thrown during template processing into TemplateException-s.
			cfg.setWrapUncheckedExceptions(true);

			recursionFile(srcDir, targetDir, srcDir, cfg);
		} catch (Throwable e) {
			log.error(e.toString(), e);
			System.exit(1);
		}
	}

	private static void recursionFile(File srcRoot, File targetRoot, File currDir, Configuration cfg) throws IOException, TemplateException {
		if (currDir.exists()) {
			File[] files = currDir.listFiles();
			if (files.length == 0) {
				log.info("文件夹是空的!");
				return;
			} else {
				for (File currFile : files) {
					if (currFile.isDirectory()) {
						log.info("文件夹:" + currFile.getCanonicalPath());
						recursionFile(srcRoot, targetRoot, currFile, cfg);
					} else {
						log.info("文件:" + currFile.getCanonicalPath());
						String templateFilePath = currFile.getCanonicalPath().substring(srcRoot.getCanonicalPath().length());
						
						String currFilePath = currFile.getCanonicalPath();
						String content = null;
						try {
							content = FreemarkerUtils.generateStringByFile(templateFilePath, cfg, model);
						} catch (Exception e) {
							content = FileUtil.readString(currFile.getCanonicalPath(), PropKit.get("file.charset", "utf-8"));
						}

						if (content != null) {
							String extension = FileNameUtil.getExtension(currFile.getCanonicalPath());

							if ("js".equalsIgnoreCase(extension)) {
								if (TioWebpackBuildStarter.model.getCompress().getJs()) {
									content = TioJsCompressor.compress(currFilePath, content);
								}
							} else if ("css".equalsIgnoreCase(extension)) {
								if (TioWebpackBuildStarter.model.getCompress().getCss()) {
									content = TioCssCompressor.compress(currFilePath, content);
								}
							} else if ("html".equalsIgnoreCase(extension) || "htm".equalsIgnoreCase(extension)) {
								if (TioWebpackBuildStarter.model.getCompress().getHtml()) {
									content = TioHtmlCompressor.compress(currFilePath, content);
								}
							}
							
							File destFile = new File(targetRoot, templateFilePath);
							if (!destFile.exists()) {
								File destDir = destFile.getParentFile();
								if (!destDir.exists()) {
									destDir.mkdirs();
								}
								destFile.createNewFile();
							}
							
							FileUtil.writeString(destFile, content, PropKit.get("file.charset", "utf-8"));
						}

					}
				}
			}
		} else {
			log.info("文件不存在!");
		}
	}

	public static void generate(Configuration cfg) {

	}
}
